package com.fire.web.modules.all.task;

import cn.hutool.core.date.DateUtil;
import com.fire.common.mybatis.mvc.wrapper.EntityWrapper;
import com.fire.web.modules.all.entity.FireSupervisorModel;
import com.fire.web.modules.all.entity.SiteModel;
import com.fire.web.modules.all.entity.TMitStaticsSiteModel;
import com.fire.web.modules.all.entity.TMitStaticsSuperiorModel;
import com.fire.web.modules.all.service.IFireSupervisorService;
import com.fire.web.modules.all.service.ISiteService;
import com.fire.web.modules.all.service.ITMitStaticsSiteService;
import com.fire.web.modules.all.service.ITMitStaticsSuperiorService;
import com.fire.web.modules.all.validation.SolrQueryDTO;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: alarmTask
 * @Description: 告警任务，主要是采集每天的告警数据并储存
 * @Author raoyuxing
 * @Date 2019/2/20 17:59
 */
@Component("alarmTask")
public class alarmTask implements ApplicationListener<ContextRefreshedEvent> {
    public final Logger log = Logger.getLogger(this.getClass());

    private Boolean isRun=Boolean.FALSE;

    @Autowired
    private SolrClient solrClient;

    @Autowired
    private ISiteService siteService;

    @Autowired
    private ITMitStaticsSuperiorService staticsSuperiorService;

    @Autowired
    private IFireSupervisorService supervisorService;

    @Autowired
    private ITMitStaticsSiteService staticsSiteService;

    @Value("${spring.data.solr.core}")
    private String core;

    private static final String[] RANGES = new String[]{"water", "electricity","gas","fire","dvr"};

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

    }

    /**
     * 获取solr中的alarm数据
     */
    public void run() {
        log.info(" 告警数据统计任务运行开始......................................" + (new Date()));
        if (!isRun) {
            isRun=Boolean.TRUE;
            try {
                SiteTask();
                superiorTask();
//                System.out.println("告警数据统计任务运行测试............" + DateUtil.format(new Date(),"yyyyMMddHHmmssSSS"));
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                isRun=Boolean.FALSE;
            }
        }
    }

    private void superiorTask(){
        EntityWrapper<FireSupervisorModel> wrapper = new EntityWrapper<>();
        List<FireSupervisorModel> list = supervisorService.selectList(wrapper);
        for (int i = 0; i < list.size(); i++) {
            saveStaticsSuperior(list.get(i));
        }

    }

    private void saveStaticsSuperior(FireSupervisorModel supervisorModel){
        EntityWrapper<SiteModel> wrapper = new EntityWrapper<>();
        wrapper.eq("supervisorid",supervisorModel.getSupervisorid());
        List<SiteModel> list = siteService.selectList(wrapper);
        for (int j = 0; j < RANGES.length; j++) {
            TMitStaticsSuperiorModel staticsSuperiorModel = new TMitStaticsSuperiorModel();
            int alarmnum = 0;
            int crisicnum = 0;
            String seqdate = DateUtil.format(DateUtil.yesterday(),"yyyyMMdd");
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    EntityWrapper<TMitStaticsSiteModel> staticsSiteWrapper = new EntityWrapper<>();
                    staticsSiteWrapper.eq("siteid", list.get(i).getSiteid());
                    staticsSiteWrapper.eq("seqdate", seqdate);
                    staticsSiteWrapper.eq("`range`", RANGES[j]);
                    TMitStaticsSiteModel siteModel = staticsSiteService.selectOne(staticsSiteWrapper);
                    alarmnum += siteModel.getAlarmnum();
                    crisicnum += siteModel.getCrisicnum();
                }
            }
            staticsSuperiorModel.setRange(RANGES[j]);
            staticsSuperiorModel.setAlarmnum(alarmnum);
            staticsSuperiorModel.setCrisicnum(crisicnum);
            staticsSuperiorModel.setSuperiorid(supervisorModel.getSupervisorid());
            staticsSuperiorModel.setCreatetime(new Date());
            staticsSuperiorModel.setSeqdate(seqdate);

            EntityWrapper<TMitStaticsSuperiorModel> superiorWrapper = new EntityWrapper<>();
            superiorWrapper.eq("seqdate",seqdate);
            superiorWrapper.eq("superiorid",staticsSuperiorModel.getSuperiorid());
            superiorWrapper.eq("`range`",RANGES[j]);
            TMitStaticsSuperiorModel result = staticsSuperiorService.selectOne(superiorWrapper);
            if (null == result) {
                staticsSuperiorService.insert(staticsSuperiorModel);
            }

        }
    }

    private void SiteTask() throws IOException, SolrServerException {

        List<SiteModel> siteModels = siteService.selectList(new SiteModel());
        int num = siteModels.size();
        int siteIndex = 0;
        while (true){
            if (num == 0){
                break;
            }

            saveStaticsSiteData(siteModels.get(siteIndex));

            siteIndex++;
            num--;
        }

    }

    private void saveStaticsSiteData(SiteModel site ) throws IOException, SolrServerException {

        for (int i = 0; i < RANGES.length; i++) {
            SolrQueryDTO alarmNumQueryDTO = new SolrQueryDTO();
            alarmNumQueryDTO.setEventType("Alert");
            alarmNumQueryDTO.setSiteToken(site.getSitetoken());
            alarmNumQueryDTO.setRange(RANGES[i]);
            alarmNumQueryDTO.setAlertLevel("*");
            int alarmNum = querySolr(alarmNumQueryDTO);

            SolrQueryDTO crisicNumQueryDTO = new SolrQueryDTO();
            crisicNumQueryDTO.setEventType("Alert");
            crisicNumQueryDTO.setSiteToken(site.getSitetoken());
            crisicNumQueryDTO.setRange(RANGES[i]);
            alarmNumQueryDTO.setAlertLevel("Critical");
            int crisicNum = querySolr(crisicNumQueryDTO);

            SolrQueryDTO measureNumQueryDTO = new SolrQueryDTO();
            measureNumQueryDTO.setEventType("Measurements");
            measureNumQueryDTO.setSiteToken(site.getSitetoken());
            measureNumQueryDTO.setRange(RANGES[i]);
            int measureNum = querySolr(measureNumQueryDTO);

//            System.out.println(RANGES[i] + "   alarmNum:"+alarmNum+"  crisicNum:"+crisicNum+"  measureNum:"+measureNum);

            TMitStaticsSiteModel siteModel = new TMitStaticsSiteModel();
            String seqdate = DateUtil.format(DateUtil.yesterday(),"yyyyMMdd");
            siteModel.setSeqdate(seqdate);
            siteModel.setCreatetime(new Date());
            siteModel.setSiteid(site.getSiteid());
            siteModel.setRange(RANGES[i]);
            siteModel.setAlarmnum(alarmNum);
            siteModel.setCrisicnum(crisicNum);
            siteModel.setMeasurenum(measureNum);

            EntityWrapper<TMitStaticsSiteModel> wrapper = new EntityWrapper<>();
            wrapper.eq("seqdate",seqdate);
            wrapper.eq("siteid",site.getSiteid());
            wrapper.eq("`range`",RANGES[i]);
            TMitStaticsSiteModel result = staticsSiteService.selectOne(wrapper);

            if (null == result) {
                staticsSiteService.insert(siteModel);
            }
        }
    }

    private int querySolr(SolrQueryDTO queryDTO) throws IOException, SolrServerException {

        SolrQuery solrQuery = new SolrQuery();
        StringBuilder params = new StringBuilder();

        if(!StringUtils.isEmpty(queryDTO.getRange())){
            params.append(" AND meta.range: " + queryDTO.getRange() );
        }
        if(!StringUtils.isEmpty(queryDTO.getEventType())){
            params.append(" AND eventType: " + queryDTO.getEventType());
        }
        if(!StringUtils.isEmpty(queryDTO.getAssetId())){
            params.append(" AND assetId: " + queryDTO.getAssetId());
        }
        if(!StringUtils.isEmpty(queryDTO.getSiteToken())){
            params.append(" AND siteToken: " + queryDTO.getSiteToken());
        }
        if(!StringUtils.isEmpty(queryDTO.getSiteName())){
            params.append(" AND siteName: " + queryDTO.getSiteName());
        }
        if(!StringUtils.isEmpty(queryDTO.getCategoryid())){
            params.append(" AND categoryid: " + queryDTO.getCategoryid());
        }
        if(!StringUtils.isEmpty(queryDTO.getCategoryname())){
            params.append(" AND categoryname: " + queryDTO.getCategoryname());
        }
        if(!StringUtils.isEmpty(queryDTO.getAlertLevel())){
            params.append(" AND alertLevel: " + queryDTO.getAlertLevel());
        }
        if(!StringUtils.isEmpty(queryDTO.getAlertSource())){
            params.append(" AND alertSource: " + queryDTO.getAlertSource());
        }

        String lastDay = DateUtil.format(DateUtil.yesterday(),"yyyy-MM-dd'T'");
        String today = DateUtil.format(new Date(),"yyyy-MM-dd'T'");
        params.append(" AND receivedDate:["+lastDay+"00:00:00Z TO "+today+"00:00:00Z}");
//        params.append(" AND receivedDate:[2019-02-10T00:00:00Z TO * ]");


        String queryString = params.toString();
        if(!StringUtils.isEmpty(queryString)){
            queryString = queryString.substring(4);
        }

        //必填条件(*:* 为默认所有数据)
        solrQuery.setQuery("*:*");
        //筛选条件, 筛选setQuery条件下的数据
        solrQuery.setFilterQueries(queryString);
        //返回结果的第几条记录开始，一般分页用，默认0开始
        solrQuery.setStart(0);
        //指定返回结果最多有多少条记录，默认值为 10，配合start实现分页
        solrQuery.setRows(Integer.MAX_VALUE);

        QueryResponse queryResponse = solrClient.query(core, solrQuery);

        return queryResponse.getResults().size();

    }
}
